package com.situ.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.entity.Student;
import com.situ.web.exception.NameRepeatException;
import com.situ.web.service.IStudentService;
import com.situ.web.service.impl.StudentServiceImpl;

public class AddStudentServlet extends HttpServlet{
	private IStudentService studentService = new StudentServiceImpl();
	
	/*@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("AddStudentServlet.doGet()");
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("AddStudentServlet.doPost()");
	}*/
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//解决post请求乱码问题，放在service方法最上面
		//req.setCharacterEncoding("UTF-8");
		//1.接收请求参数，封装成对象
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		Student student = new Student(name, Integer.parseInt(age), gender);
		System.out.println(student);
		//2.调用业务层进行处理
		boolean isSuccess = false;
		try {
			 isSuccess = studentService.register(student);
		} catch (NameRepeatException e) {
			e.printStackTrace();
		}
		//3.将处理结果返回给浏览器
		//重定向是给浏览器看的，所以/Java1812Web前面的"/"代表tomcat目录
		resp.sendRedirect(req.getContextPath() + "/findAllStudent");
		//req.getRequestDispatcher("/findAllStudent").forward(req, resp);
		
		/*resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		if (isSuccess) {
			writer.println("注册成功");
		} else {
			writer.println("注册失败");
		}
		writer.close();*/
	}
}
